﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tierless.Framework.ServiceContracts;
using Tierless.Framework.Data;
using Tierless.Framework.EntityTypes;

namespace Tierless.Framework.Client
{
	public class EntityService : IEntityService
	{
		public EntityService()
		{
			Client = new EntityClient();
		}

		public EntityClient Client { get; private set; }

		public List<Data.EntitySet> Get(Data.EntityRequests lookupRequest)
		{
			var result = Client.Get(lookupRequest);

			// Ensure that all associated entity types are loaded
			if (EntityTypeRepository.EntityTypeProvider != null)
			{
				HashSet<string> typeNames = new HashSet<string>();
				foreach (var set in result)
					if (!typeNames.Contains(set.EntityTypeName))
						typeNames.Add(set.EntityTypeName);
				EntityTypeRepository.EntityTypeProvider.EnsureEntityTypes(typeNames);
			}

			return result;
		}

		public EntitySaveResult Save(List<Data.EntitySet> entitySets)
		{
			return Client.Save(entitySets);
		}

		public EntityType[] Describe(string[] entityNames)
		{
			return Client.Describe(entityNames);
		}
	}
}
